<template>
  <!-- 搜索 -->
  <ContentWrap :show-border="false">
    <SearchBox
      :queryForm="searchList"
      :showExpland="true"
      :show-export="false"
      @changeVal="handleChange"
      @query="handleSearchQuery"
    />
  </ContentWrap>

  <ContentWrap :show-border="false" :bodyStyle="{ padding: '0 10px 10px 0' }">
    <OrderStatusMenu :list="statusList" @tabChange="handleOrderStatus" />
  </ContentWrap>

  <!-- 批量操作 -->
  <ContentWrap :show-border="false" :bodyStyle="{ padding: '0 10px 10px 0' }">
    <BatchAction
      :total="total"
      :sort="orderSortType"
      :selectedRows="selectedRows"
      :status="queryParams.afterSales"
      @updateList="getList"
      @updateSort="updateSortType"
      @exportRun="handleExport"
    />
  </ContentWrap>
  <ContentWrap :show-border="false">
    <OrderTable :list="list" @updateList="getList" @selectionChange="handleSelectionChange" />
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" setup>
import { getSimpleDeptList } from '@/api/system/dept'
import { getUserPage } from '@/api/system/user'
import { getUserPageNew } from '@/api/member/user'
import { getGlobeState } from '@/api/publicInterf'
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
import * as PickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { createImageViewer } from '@/components/ImageViewer'
import { TabsPaneContext } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { fenToYuan, buildTree, deepCopy } from '@/utils'
import type { TradeOrderQueryVO } from '@/api/mall/trade/order'
import * as TradeOrderApi from '@/api/mall/trade/order'
import download from '@/utils/download'
import { getDeptPage } from '@/api/system/dept'

import OrderStatusMenu from '../components/OrderStatusMenu.vue'
import BatchAction from './components/BatchAction.vue'
import { OrderTableColumn } from './components'
import OrderTable from './components/OrderTable.vue'
import { usePageLoading } from '@/hooks/web/usePageLoading'

const { loadStart, loadDone } = usePageLoading()

const message = useMessage()

defineOptions({ name: 'TradeAfterSale' })

const { push } = useRouter() // 路由跳转

type SortType = 'DESC' | 'ASC'

const orderSortType = ref('DESC')

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<AfterSaleApi.TradeAfterSaleVO[]>([]) // 列表的数据
const statusTabs = ref([
  {
    label: '全部',
    value: '0'
  }
])

const selectedRows = ref([])

const depatList = ref([])

const createNameList = ref([])

const areaList = ref([])

const createList = ref([])

const queryFormRef = ref() // 搜索的表单
const pickUpStoreList = ref<PickUpStoreApi.DeliveryPickUpStoreVO[]>([]) // 自提门店精简列表

const initQueryParams = {
  pageNo: 1,
  pageSize: 10,
  afterSales: 1, // 售后订单 1全部 2待处理 3已作废
  orderNo: null,
  createTime: [],
  // type: null,
  sort: orderSortType.value,
}
// 查询参数
const queryParams = ref({
  ...initQueryParams
})

const searchList = ref<TradeOrderQueryVO[]>([
  {
    label: '订单号',
    code: 'orderNo',
    type: 'input'
  },

  {
    label: '商品信息',
    code: 'product',
    type: 'input',
    placeholder: '商品名称/商品ID/sku'
  },
  {
    label: '创建部门',
    code: 'deptId',
    type: 'treeSelect',
    options: []
  },
  {
    label: '创建者',
    code: 'userId',
    type: 'select',
    options: []
  },
  {
    label: '下单日期',
    code: 'createTime',
    type: 'dateRange'
  },
  {
    label: '地区',
    code: 'areaId',
    type: 'select',
    options: []
  },
  {
    label: '下单信息',
    code: 'customerName',
    type: 'input',
    placeholder: '下单姓名/联系方式'
  }
])

const initOrderStatusList =ref( 
  [
  {
    label: '全部订单',
    value: 1
  },
  {
    label: '待处理',
    value: 2
  },
  {
    label: '已作废',
    value: 3
  }
]
)

const statusList = ref(deepCopy(initOrderStatusList.value))

const handleOrderStatus = (status: number) => {
  //获取指定订单状态
  // console.log(status, 'status')
  queryParams.value = {
    ...initQueryParams,
    afterSales: status
  }
  getList()
}

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
  if (val.createTime && val.createTime.length) {
    val.startDate = val.createTime[0]
    val.endDate = val.createTime[1]
  }
  delete val.createTime
  queryParams.value = {
    ...initQueryParams,
    ...val,
    afterSales: queryParams.value.afterSales
  }
  getList()
}
const getStatusAccount = async () =>{
  const res = await TradeOrderApi.getAllOrderNum()
  statusList.value = deepCopy(initOrderStatusList.value).map((item)=>{
    if(item.value === 1 ){
      item.label += `(${res.afterSalePendingCount + res.cancelledCount })`
    }else if(item.value === 2 ){
      item.label += `(${res.afterSalePendingCount})`
    }else if(item.value === 3 ){
      item.label += `(${res.cancelledCount})`
    }
    return item
  })
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  getStatusAccount()
  try {
    const data = cloneDeep(queryParams.value)

    // 执行查询
    const res = await TradeOrderApi.getOrderPage(queryParams.value)
    list.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.value.pageNo = 1
  await getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** tab 切换 */
const tabClick = async (tab: TabsPaneContext) => {
  queryParams.value.afterSales = tab.paneName
  await getList()
}

/** 处理退款 */
const openAfterSaleDetail = (id: number) => {
  push({ name: 'TradeAfterSaleDetail', params: { id } })
}

/** 查看订单详情 */
const openOrderDetail = (id: number) => {
  push({ name: 'TradeOrderDetail', params: { id } })
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/**
 * 获取用户选中的行数据
 */
const handleSelectionChange = (val: any) => {
  selectedRows.value = val
}

// const initPromise = async () => {
//   let res = await Promise.all([getDeptPage()])
//   console.log(res, 'res')
//   let item = searchList.value.find((at) => {
//     return at.code == 'deptId'
//   })
//   console.log(item)
//   item.options = res[0]
//   console.log(res[0])
// }

//查询部门人员
const getCreateNameList = async () => {
  const res = await getUserPageNew({
    pageNo: 1,
    pageSize: 99,
    deptId: queryParams.value.deptId || null
  })
  createNameList.value = res.map((item) => {
    return {
      label: item.nickname,
      value: item.id
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'userId') {
      item.options = createNameList.value
    }
  })
}

const handleChange = (val) => {
  console.log(val, 'handleChange')
  if (val.form.deptId) {
    queryParams.value.deptId = val.form.deptId
  }
}
watch(
  () => queryParams.value.deptId,
  () => {
    if (queryParams.value.deptId) {
      getCreateNameList()
    }
  }
)

/** 导出按钮操作 */
const handleExport = async (val: any) => {
  try {
    // 导出的二次确认
    // await message.exportConfirm()
    // 发起导出
    const {orderNos,curStatus} = val;
    queryParams.value.afterSales = curStatus
    loadStart()
    if (val) {
      const data = await TradeOrderApi.exportOrderExcelData({orderNo:orderNos,afterSales:curStatus})
      download.excel(data, '售后订单列表.xls')
    } else {
      const data = await TradeOrderApi.exportOrderExcelData(queryParams.value)
      download.excel(data, '售后订单列表.xls')
    }
  } catch {
  } finally {
    loadDone()
  }
}

const init = async () => {
  const [depatRes, areaRes] = await Promise.all([
    getSimpleDeptList(),
    getGlobeState({ pageNum: 1, pageSize: 100 })
  ])
  depatList.value = buildTree(depatRes)
  searchList.value.map((item) => {
    if (item.code === 'deptId') {
      item.options = depatList.value
    }
  })
  areaList.value = areaRes.map((item) => {
    return {
      label: item.stateName,
      value: item.id
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'areaId') {
      item.options = areaList.value
    }
  })
}





onMounted(async () => {
  
  init()
  getCreateNameList()
  nextTick(() => {
    getList()
  })
  // await getList()
  // // 设置 statuses 过滤
  // for (const dict of getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_STATUS)) {
  //   statusTabs.value.push({
  //     label: dict.label,
  //     value: dict.value
  //   })
  // }
  // initPromise()
})

const updateSortType = async (val: 'DESC' | 'ASC') => {
  orderSortType.value = val
  queryParams.value.sort = val
  await getList()
}
</script>
<style lang="scss" scoped>
:deep(.subTable .el-table__inner-wrapper::before) {
  height: 0px !important;
}

:deep(.subTable .el-table td.el-table__cell) {
  border-bottom: 0px !important;
}

:deep(.el-table tr.tableRow) {
  background-color: #fff;
  position: relative !important;
  padding-top: 30px !important;
  height: 100px;
}

:deep(.el-table td.btnColumn) {
  z-index: 9 !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  background-color: #fff;
}

:deep(.el-table .el-table__cell.mergeRow) {
  position: absolute;
  width: 100%;
  left: 0px;
  top: 0;
  padding-left: 52px;
  background-color: transparent;
  border-bottom: 0px !important;
  z-index: 9;
  background-color: #fbfbfd;
  padding-top: 0;
  padding-bottom: 0;
}
</style>
